package com.haike.pushjobs.config;


import cn.hutool.Hutool;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.ClassUtils;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

@Slf4j
@Configuration
public class QuartzInitializer {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private JobConfig jobConfig;

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void init() throws SchedulerException {
        List<JobConfig.JobProperties> jobs = jobConfig.getJobs();
        if (jobs != null) {
            for (JobConfig.JobProperties jobProp : jobs) {
                try {
                    if (!jobProp.isEnabled()) {
                        log.info("跳过Job {} is disabled, skipping...", jobProp.getName());
                        continue;
                    }

                    Class<? extends Job> jobClass = (Class<? extends Job>) ClassUtils.forName(jobProp.getClassName(), this.getClass().getClassLoader());

                    JobDetail jobDetail = JobBuilder.newJob(jobClass)
                            .withIdentity(jobProp.getName(), jobProp.getGroup())
                            .withDescription(jobProp.getDescription())
                            .usingJobData("param", jobProp.getParam()) // 传递参数
                            .storeDurably()
                            .build();

                    Trigger trigger;
                    if (jobProp.getCron() != null && !jobProp.getCron().isEmpty()) {
                        trigger = TriggerBuilder.newTrigger()
                                .forJob(jobDetail)
                                .withIdentity(jobProp.getName() + "Trigger", jobProp.getGroup())
                                .withSchedule(CronScheduleBuilder.cronSchedule(jobProp.getCron()))
                                .build();
                    } else if (jobProp.getFixedRate() != null && jobProp.getFixedRate() > 0) {
                        trigger = TriggerBuilder.newTrigger()
                                .forJob(jobDetail)
                                .withIdentity(jobProp.getName() + "Trigger", jobProp.getGroup())
                                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                                        .withIntervalInMilliseconds(jobProp.getFixedRate())
                                        .repeatForever())
                                .build();
                    } else {
                        throw new IllegalArgumentException("Either cron or fixedRate must be set for job: " + jobProp.getName());
                    }

                    if (!scheduler.checkExists(jobDetail.getKey())) {
                        scheduler.scheduleJob(jobDetail, trigger);

                        log.info("[job:{}]启动", jobProp.getName());
                        // 列出下5次执行时间
                        var fireTime = new Date();
                        for (int i = 0; i < 5; i++) {
                            log.info("[job:{}]第{}次执行时间: {}", jobProp.getName(), i + 1, DateUtil.format(trigger.getFireTimeAfter(fireTime), "yyyy-MM-dd HH:mm:ss"));
                            fireTime = trigger.getFireTimeAfter(fireTime);
                        }

                        if (jobProp.getCron() != null && !jobProp.getCron().isEmpty()) {
                            // 立即执行
                            scheduler.triggerJob(jobDetail.getKey());
                        }
                    }
                } catch (ClassNotFoundException e) {
                    throw new SchedulerException("Job class not found: " + jobProp.getClassName(), e);
                }
            }
        }
    }
}    